package com.qiangesoft.rdp.starter.captcha.core;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.qiangesoft.rdp.starter.captcha.config.CaptchaProperties;

import java.util.concurrent.TimeUnit;

/**
 * 验证码存储服务
 *
 * @author qiangesoft
 * @date 2023-09-19
 */
public class CaptchaLocalStoreImpl implements CaptchaStore {

    private final CaptchaProperties captchaProperties;

    private final Cache<String, String> localCache;

    public CaptchaLocalStoreImpl(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
        localCache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterAccess(captchaProperties.getExpiration(), TimeUnit.SECONDS)
                .build();
    }

    @Override
    public void put(String key, String value) {
        localCache.put(key, value);
    }

    @Override
    public String get(String key) {
        return localCache.getIfPresent(key);
    }

    @Override
    public void remove(String key) {
        localCache.invalidate(key);
    }

    @Override
    public void clear() {
        localCache.cleanUp();
    }
}
